package com.hakim.wfb.customer.service.impl;

import com.hakim.wfb.bean.*;
import com.hakim.wfb.biz.CreditPointBiz;
import com.hakim.wfb.biz.PointOrderBiz;
import com.hakim.wfb.common.enums.CustomerOrderStatusEnum;
import com.hakim.wfb.customer.params.goods.PurchaseListParameter;
import com.hakim.wfb.customer.params.order.AddOrderParameter;
import com.hakim.wfb.customer.params.order.CancelOrderParameter;
import com.hakim.wfb.customer.result.order.OrderListView;
import com.hakim.wfb.customer.result.purchase.PurchaseListView;
import com.hakim.wfb.customer.service.PurchaseService;
import com.hakim.wfb.dao.*;
import com.hkfs.fundamental.api.data.ListResultEx;
import com.hkfs.fundamental.api.data.ResultEx;
import com.hakim.wfb.common.enums.PointTypeEnum;
import com.hakim.wfb.common.enums.TransTypeEnum;
import com.hakim.wfb.common.serial.SerialNoGenerator;
import com.hakim.wfb.common.serial.UUIDGenerator;
import com.hakim.wfb.common.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by lenovo on 2017/7/3.
 */
@Service("purchaseService")
public class PurchaseServiceImpl implements PurchaseService {

    @Autowired
    private PurchaseListDao purchaseListDao;

    @Autowired
    private OrderListDao orderListDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private PointOrderBiz pointOrderBiz;

    @Autowired
    private CreditPointDao creditPointDao;

    @Autowired
    private CreditPointBiz creditPointBiz;

    @Autowired
    private GoodsListDao goodsListDao;

    @Override
    public ListResultEx<PurchaseListView> getChartList(PurchaseListParameter param) {
        ListResultEx<PurchaseListView> res = new ListResultEx<PurchaseListView>();
        try {
            int count = purchaseListDao.getChartListCount(param);
            res.setTotalCount(count);
            if (count > 0) {
                res.setDataList(purchaseListDao.getChartList(param));
            } else {
            }
        } catch (Exception e) {
            return res.makeFailedResult();
        }
        return res.makeSuccessResult();
    }

    @Override
    @Transactional
    public ResultEx addOrder(AddOrderParameter parameter) {
        ResultEx res = new ResultEx();
        try {

            String orderno = SerialNoGenerator.getGoodsOrderNo(parameter.getPhone());

            Map<String, Integer> idMap = new HashMap<String, Integer>();
            String[] tids = parameter.getPurchaseId().split(",");
            String listStr = "";
            for (int i = 0; i < tids.length; i++) {
                if (tids[i].length() == 0) continue;
                if (!idMap.containsKey(tids[i])) {
                    idMap.put(tids[i], 1);
                    listStr += ",'" + tids[i] + "'";
                } else {
                    idMap.put(tids[i], idMap.get(tids[i]) + 1);
                }
            }

            // 校验电子积分是否足够， 写入积分变动表
            double sumPoint = 0;//purchaseListDao.getChartSum(listStr.substring(1));
            for (Map.Entry<String, Integer> ky : idMap.entrySet()) {
                sumPoint += purchaseListDao.getChartSum(ky.getKey()) * idMap.get(ky.getKey());
            }

            User user = userDao.getById(parameter.getUserId());

            CreditPoint creditPoint = creditPointBiz.getCreditPoint(parameter.getUserId());
            if (creditPoint == null) {
                return res.makeFailedResult("用户不存在");
            }
            if (creditPoint.getCpElecPoint() < sumPoint) {
                return res.makeFailedResult("电子积分不足");
            }
            // 校验电子积分是否足够， 写入积分变动表
            // 订单列表
            OrderList order = new OrderList();
            order.setOlCreateDate(new Date());
            order.setOlOrderno(orderno);
            order.setStatus(CustomerOrderStatusEnum.NOT_SEND.getValue()); // 1. 待发货； 2. 已发货； 3. 待签收； 4. 已签收
            order.setOlSum(BigDecimal.valueOf(sumPoint));
            order.setOlUpdateDate(new Date());
            order.setOlUser(user.getTid());
            order.setTid(UUIDGenerator.getUUID());
            order.setOlAddr(parameter.getRaAddr());
            orderListDao.add(order);
            // 订单列表
            if (parameter.getPurchaseId().contains(",")) {
//                Map<String, String> map = new HashMap<String, String>();
//                map.put("ids", "(" + purchaseid + ")");
//                map.put("orderno", orderno);
//                map.put("updat", DateUtils.getStringDate());
//                purchaseListDao.updateByIds(map);
                for (int i = 0; i < tids.length; i++) {
                    PurchaseList pl = new PurchaseList();
                    pl.setTid(tids[i]);
                    pl.setPlOrderno(orderno);
                    pl.setPlUpdateDate(new Date());
                    purchaseListDao.update(pl);
                }
            } else {
                PurchaseList pl = new PurchaseList();
                pl.setTid(parameter.getPurchaseId());
                pl.setPlOrderno(orderno);
                pl.setPlUpdateDate(new Date());
                purchaseListDao.update(pl);
            }

            // 交易成功写积分变动信息
            creditPoint.setCpElecPoint(creditPoint.getCpElecPoint() - sumPoint);
            creditPoint.setCpOriginalPoint(creditPoint.getCpOriginalPoint() + sumPoint);
            creditPointDao.update(creditPoint);

            //系统为正数
            //电子积分
            PointOrder elecPointOrderPlus = new PointOrder();
            elecPointOrderPlus.setTid(UUIDGenerator.getUUID());
            elecPointOrderPlus.setPoAmount(0);
            elecPointOrderPlus.setPoCreateDate(DateUtils.getNow());
            elecPointOrderPlus.setPoDescription("购物车订单号【" + orderno + "】系统收到" + user.getUserCode() + "电子积分：" + sumPoint);
            elecPointOrderPlus.setPoFromUser(parameter.getUserId());
            elecPointOrderPlus.setPoOrderno(orderno);
            elecPointOrderPlus.setPoPointType(PointTypeEnum.ELEC_POINT.getValue());
            elecPointOrderPlus.setPoToUser("0");
            elecPointOrderPlus.setPoTransPoint(sumPoint);
            elecPointOrderPlus.setPoType(TransTypeEnum.ELTOORG.getValue());
            pointOrderBiz.add(elecPointOrderPlus);

            //增加积分变动流水记录 用户为负数
            PointOrder elecPointOrderMinus = new PointOrder();
            elecPointOrderMinus.setTid(UUIDGenerator.getUUID());
            elecPointOrderMinus.setPoAmount(creditPoint.getCpElecPoint());
            elecPointOrderMinus.setPoCreateDate(DateUtils.getNow());
            elecPointOrderMinus.setPoDescription("购物车订单号【" + orderno + "】用户" + user.getUserCode() + "支出电子积分：" + (sumPoint * -1));
            elecPointOrderMinus.setPoFromUser("0");
            elecPointOrderMinus.setPoOrderno(orderno);
            elecPointOrderMinus.setPoPointType(PointTypeEnum.ELEC_POINT.getValue());
            elecPointOrderMinus.setPoToUser(user.getTid());
            elecPointOrderMinus.setPoTransPoint(sumPoint * -1);
            elecPointOrderMinus.setPoType(TransTypeEnum.ELTOORG.getValue());
            pointOrderBiz.add(elecPointOrderMinus);

            //原始积分
            PointOrder orgPointOrderMinus = new PointOrder();
            orgPointOrderMinus.setTid(UUIDGenerator.getUUID());
            orgPointOrderMinus.setPoAmount(0);
            orgPointOrderMinus.setPoCreateDate(DateUtils.getNow());
            orgPointOrderMinus.setPoDescription("购物车订单号【" + orderno + "】系统支出" + user.getUserCode() + "原始积分：" + (sumPoint * -1));
            orgPointOrderMinus.setPoFromUser(parameter.getUserId());
            orgPointOrderMinus.setPoOrderno(orderno);
            orgPointOrderMinus.setPoPointType(PointTypeEnum.ORIGINAL_POINT.getValue());
            orgPointOrderMinus.setPoToUser("0");
            orgPointOrderMinus.setPoTransPoint(sumPoint * -1);
            orgPointOrderMinus.setPoType(TransTypeEnum.ELTOORG.getValue());
            pointOrderBiz.add(orgPointOrderMinus);

            //增加积分变动流水记录 用户为负数
            PointOrder orgPointOrderPlus = new PointOrder();
            orgPointOrderPlus.setTid(UUIDGenerator.getUUID());
            orgPointOrderPlus.setPoCreateDate(DateUtils.getNow());
            orgPointOrderPlus.setPoDescription("购物车订单号【" + orderno + "】用户" + user.getUserCode() + "收到原始积分：" + sumPoint);
            orgPointOrderPlus.setPoFromUser("0");
            orgPointOrderPlus.setPoOrderno(orderno);
            orgPointOrderPlus.setPoPointType(PointTypeEnum.ORIGINAL_POINT.getValue());
            orgPointOrderPlus.setPoToUser(user.getTid());
            orgPointOrderPlus.setPoTransPoint(sumPoint);
            orgPointOrderPlus.setPoAmount(creditPoint.getCpOriginalPoint());
            orgPointOrderPlus.setPoType(TransTypeEnum.ELTOORG.getValue());
            pointOrderBiz.add(orgPointOrderPlus);

            // 交易成功写积分变动信息

        } catch (Exception e) {
            return res.makeFailedResult();
        }
        return res.makeSuccessResult();
    }

    @Override
    @Transactional
    public ResultEx cancelOrder(CancelOrderParameter parameter) {
        ResultEx re = new ResultEx();
        try {

            OrderList orderListParam = new OrderList();
            orderListParam.setTid(parameter.getOrderId());
            OrderList orderList = orderListDao.get(orderListParam);

            User user = userDao.getById(orderList.getOlUser());

            CreditPoint creditPoint = creditPointBiz.getCreditPoint(orderList.getOlUser());
            if (creditPoint == null) {
                return re.makeFailedResult("用户不存在");
            }
            double userPoint = creditPoint.getCpOriginalPoint();
            if (userPoint < orderList.getOlSum().doubleValue()) {
                return re.makeFailedResult("原始积分不足");
            }
            orderListDao.cancelOrder(parameter.getOrderId());

            // 交易成功写积分变动信息
            CreditPoint cp = creditPointDao.getById(orderList.getOlUser());
            cp.setCpOriginalPoint(cp.getCpOriginalPoint() - orderList.getOlSum().doubleValue());
            cp.setCpElecPoint(cp.getCpElecPoint() + orderList.getOlSum().doubleValue());
            cp.setTid(cp.getTid());
            creditPointDao.update(cp);

            //系统为正数
            PointOrder custPointOrder = new PointOrder();
            custPointOrder.setTid(UUIDGenerator.getUUID());
            custPointOrder.setPoAmount(0);
            custPointOrder.setPoCreateDate(DateUtils.getNow());
            custPointOrder.setPoDescription("购物车订单号【" + parameter.getOrderId() + "】撤销，系统支出" + user.getUserCode() + "电子积分：" + (orderList.getOlSum().doubleValue() * -1));
            custPointOrder.setPoFromUser(user.getTid());
            custPointOrder.setPoOrderno(parameter.getOrderId());
            custPointOrder.setPoPointType(PointTypeEnum.ELEC_POINT.getValue());
            custPointOrder.setPoToUser("0");
            custPointOrder.setPoTransPoint(orderList.getOlSum().doubleValue());
            custPointOrder.setPoType(TransTypeEnum.ELTOORG.getValue());
            pointOrderBiz.add(custPointOrder);

            //增加积分变动流水记录 用户为负数
            PointOrder reverseCustPointOrder = new PointOrder();
            reverseCustPointOrder.setTid(UUIDGenerator.getUUID());
            reverseCustPointOrder.setPoAmount(creditPoint.getCpCustPoint());
            reverseCustPointOrder.setPoCreateDate(DateUtils.getNow());
            reverseCustPointOrder.setPoDescription("购物车订单号【" + parameter.getOrderId() + "】撤销，用户" + user.getUserCode() + "得到电子积分：" + orderList.getOlSum().doubleValue());
            reverseCustPointOrder.setPoFromUser("0");
            reverseCustPointOrder.setPoOrderno(parameter.getOrderId());
            reverseCustPointOrder.setPoPointType(PointTypeEnum.ELEC_POINT.getValue());
            reverseCustPointOrder.setPoToUser(user.getTid());
            reverseCustPointOrder.setPoTransPoint(orderList.getOlSum().doubleValue() * -1);
            reverseCustPointOrder.setPoType(TransTypeEnum.ELTOORG.getValue());
            pointOrderBiz.add(reverseCustPointOrder);

            //系统为正数
            PointOrder orgPointOrder = new PointOrder();
            orgPointOrder.setTid(UUIDGenerator.getUUID());
            orgPointOrder.setPoAmount(0);
            orgPointOrder.setPoCreateDate(DateUtils.getNow());
            orgPointOrder.setPoDescription("购物车订单号【" + parameter.getOrderId() + "】撤销，系统支出" + user.getUserCode() + "原始积分：" + orderList.getOlSum().doubleValue());
            orgPointOrder.setPoFromUser(user.getTid());
            orgPointOrder.setPoOrderno(parameter.getOrderId());
            orgPointOrder.setPoPointType(PointTypeEnum.ORIGINAL_POINT.getValue());
            orgPointOrder.setPoToUser("0");
            orgPointOrder.setPoTransPoint(orderList.getOlSum().doubleValue() * -1);
            orgPointOrder.setPoType(TransTypeEnum.ELTOORG.getValue());
            pointOrderBiz.add(orgPointOrder);

            //增加积分变动流水记录 用户为负数
            PointOrder reverseOrgPointOrder = new PointOrder();
            reverseOrgPointOrder.setTid(UUIDGenerator.getUUID());
            reverseOrgPointOrder.setPoAmount(creditPoint.getCpCustPoint());
            reverseOrgPointOrder.setPoCreateDate(DateUtils.getNow());
            reverseOrgPointOrder.setPoDescription("购物车订单号【" + parameter.getOrderId() + "】撤销，用户" + user.getUserCode() + "收到原始积分：" + (orderList.getOlSum().doubleValue() * -1));
            reverseOrgPointOrder.setPoFromUser("0");
            reverseOrgPointOrder.setPoOrderno(parameter.getOrderId());
            reverseOrgPointOrder.setPoPointType(PointTypeEnum.ORIGINAL_POINT.getValue());
            reverseOrgPointOrder.setPoToUser(user.getTid());
            reverseOrgPointOrder.setPoTransPoint(orderList.getOlSum().doubleValue());
            reverseOrgPointOrder.setPoType(TransTypeEnum.ELTOORG.getValue());
            pointOrderBiz.add(reverseOrgPointOrder);

            // 交易成功写积分变动信息

            re.makeSuccessResult();

        } catch (Exception e) {
            return re.makeFailedResult("操作失败");
        }
        return re;
    }

}
